// 订单详情
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 显示优惠券列表
    coupon:false,
    product:[],
    shop_name:"",
    // 从商品详情页过来的商品ID
    p_id:"",
    // 从商品详情页过来的商品属性
    attr_val:"",
     // 从商品详情页过来的商品数量
    num: 0,
    // 商家id
    shop_id:"",
    head_pic:"",
    // coming=1,是从购物车过来的，coming=0是从商品详情页过来的
    coming:"",
    address:"",
    // 优惠券列表
    coupons:[],
    // 选中的优惠券的id
    c_m_id:"",
    // 选中的优惠券的index
    index:"",
    // 优惠的金额
    money:0,
    // 总金额
    total:"",
    // 优惠后的价格
    realPrice:"",
    // 运费价格
    postage:"",
    // 从购物车过来时传的cart_id，结算时使用
    cart_id:"",
    // 买家留言
    remark:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.getStorage({
      key: 'address',
      success: function(res) {
        var address = res.data;
        this.setData({
          address:address
        })
      }.bind(this),
    })
    // storage的第一个数，1代表从购物车过来的，0代表从详情页直接购买
    wx.getStorage({
      key: 'storage',
      success: function(res) {
        var storage = res.data;
        var coming = storage[0];
        var cart_id = "";
        var shop_id = "";
        // 从购物车购买
        if (coming == 1){
          cart_id = storage[1];
          shop_id = storage[2];
          wx.request({
            url: app.globalData.yuming +'merchant.php/Api/ProductOrder/firmOrder',
            data:{
              cart_id: cart_id,
              shop_id: shop_id
            },
            header:{
              "content-type":"application/x-www-form-urlencoded"
            },
            method:"POST",
            success:function(res){
                var shop_name = res.data.data.detail.shop_name;
                var head_pic = res.data.data.detail.head_pic;
                var product = res.data.data.detail.product;
                var total = res.data.data.total;
                var postage = 0.00;
                product.map(function(val){
                  postage = Number(postage) + Number(val.postage*val.num);
                })
             
                // product.map(function(val){
                //     total = total + Number(val.num*val.price)
                // })
                var realPrice = total;
                this.setData({
                  shop_name:shop_name,
                  head_pic:head_pic,
                  product:product,
                  total:total,
                  coming: coming,
                  cart_id:cart_id,
                  shop_id: shop_id,
                  realPrice: realPrice,
                  postage: postage
                })
                
            }.bind(this),
            fail:function(res){

            }

          })
        }
        // 从详情页直接购买
        if (coming == 0){
          var shop_id = storage[1];
          var p_id = storage[2];
          var attr_val = storage[3];
          var num = storage[4];
          var data = {};
          if(attr_val == ""){
            data= {
              shop_id: shop_id,
              p_id: p_id,
              num: num
            }
          }else{
            data= {
              shop_id: shop_id,
              p_id:p_id,
              attr_val:attr_val,
              num:num
            }
          }
          wx.request({
            url: app.globalData.yuming + 'merchant.php/Api/ProductOrder/oneFirmOrder',
            data: data,
            header:{
              "content-type":"application/x-www-form-urlencoded"
            },
            method:"POST",
            success:function(res){
              var shop_name = res.data.data.detail.shop_name;
              var head_pic = res.data.data.detail.head_pic;
              var product = res.data.data.detail.product;
              var postage = 0.00;           
              postage = Number(product.postage * product.num);
              
              var products = this.data.product;
              products[0] = product;
              // var total = Number(product.num * product.price)
              var total = res.data.data.total;
              var realPrice = total;
              this.setData({
                shop_name: shop_name,
                head_pic: head_pic,
                product: products,
                total: total,
                coming: coming,
                shop_id: shop_id,
                p_id: p_id,
                attr_val: attr_val,
                num: num,
                realPrice: realPrice,
                postage: postage
              })
            }.bind(this),
            fail:function(res){
                wx.showModal({
                  title: '提示',
                  content: res.data.message,
                  showCancel:false
                })
            }
          })
        }
      }.bind(this),
      fail:function(){
        console.log("3")
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.getStorage({
      key: 'address',
      success: function (res) {
        var address = res.data;
        this.setData({
          address: address
        })
      }.bind(this),
    })
    // storage的第一个数，1代表从购物车过来的，0代表从详情页直接购买
    wx.getStorage({
      key: 'storage',
      success: function (res) {
        var storage = res.data;
        var coming = storage[0];
        var cart_id = "";
        var shop_id = "";
        // 从购物车购买
        if (coming == 1) {
          cart_id = storage[1];
          shop_id = storage[2];
          wx.request({
            url: app.globalData.yuming + 'merchant.php/Api/ProductOrder/firmOrder',
            data: {
              cart_id: cart_id,
              shop_id: shop_id
            },
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            method: "POST",
            success: function (res) {
              var shop_name = res.data.data.detail.shop_name;
              var head_pic = res.data.data.detail.head_pic;
              var product = res.data.data.detail.product;
              var total = res.data.data.total;
              var postage = 0.00;
              product.map(function (val) {
                postage = Number(postage) + Number(val.postage * val.num);
              })
             
              // product.map(function(val){
              //     total = total + Number(val.num*val.price)
              // })
              var realPrice = total;
              this.setData({
                shop_name: shop_name,
                head_pic: head_pic,
                product: product,
                total: total,
                coming: coming,
                cart_id: cart_id,
                shop_id: shop_id,
                realPrice: realPrice,
                postage: postage
              })

            }.bind(this),
            fail: function (res) {
              wx.showModal({
                title: '提示',
                content: res.data.message,
                showCancel:false
              })
            }

          })
        }
        // 从详情页直接购买
        if (coming == 0) {
          var shop_id = storage[1];
          var p_id = storage[2];
          var attr_val = storage[3];
          var num = storage[4];
          var data = {};
          if (attr_val == "") {
            data = {
              shop_id: shop_id,
              p_id: p_id,
              num: num
            }
          } else {
            data = {
              shop_id: shop_id,
              p_id: p_id,
              attr_val: attr_val,
              num: num
            }
          }
          wx.request({
            url: app.globalData.yuming + 'merchant.php/Api/ProductOrder/oneFirmOrder',
            data: data,
            header: {
              "content-type": "application/x-www-form-urlencoded"
            },
            method: "POST",
            success: function (res) {
              var shop_name = res.data.data.detail.shop_name;
              var head_pic = res.data.data.detail.head_pic;
              var product = res.data.data.detail.product;
              var postage = 0.00;
              postage = Number(product.postage * product.num);
              
              var products = this.data.product;
              products[0] = product;
              // var total = Number(product.num * product.price)
              var total = res.data.data.total;
              var realPrice = total;
              this.setData({
                shop_name: shop_name,
                head_pic: head_pic,
                product: products,
                total: total,
                coming: coming,
                shop_id: shop_id,
                p_id: p_id,
                attr_val: attr_val,
                num: num,
                realPrice: realPrice,
                postage: postage
              })
            }.bind(this),
            fail: function (res) {
              wx.showModal({
                title: '提示',
                content: res.data.message,
                showCancel: false
              })
            }
          })
        }
      }.bind(this),
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: res.data.message,
          showCancel:false
        })
      }
    })
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: app.globalData.name,
      path: "/pages/shouye/shouye",
      imageUrl: app.globalData.headPic
    }
  },
  /**
  * 选择优惠券
  */
  chooseCoupon: function () {
    var coupon = this.data.coupon;
    this.setData({
      coupon: !coupon
    });
    // 获取优惠券
    var m_id = app.globalData.user.m_id;
    var p =1;
    wx.request({
      url: app.globalData.yuming + 'merchant.php/Api/Coupon/couponList',
      data: {
        m_id:m_id,
        status:0,
        p:p
      },
      header: {
        "content-type":"application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: function(res) {
        var coupons = res.data.data;
        this.setData({
          coupons:coupons
        })
      }.bind(this),
      fail: function(res) {
          wx.showModal({
            title: '提示',
            content: res.data.message,
          })
      }
    })
  },
  /**
   * 选择优惠券完成
   */
  complate: function () {
    var coupon = this.data.coupon;
    this.setData({
      coupon: !coupon
    })
  },
  /**
   * 调取收货地址
   */
  address:function(){
    wx.chooseAddress({
      success:(res)=>{
        var address = res;
        this.setData({
          address:address
        })
        wx.setStorage({
          key: 'address',
          data: address,
        })
      }
    })
  },
  // 点击使用优惠券
  useCoupon:function(e){
    var c_m_id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    var coupon = !this.data.coupon;
    var coupons = this.data.coupons;
    // 优惠的金额
    var total = this.data.total;
    var money = coupons[index].money;
    var realPrice = "";
    if (total > money){
      realPrice = Number(total) - Number(money)
    }else{
      realPrice = 0
    }
    // 判断优惠券金额与总价的大小
      this.setData({
        c_m_id: c_m_id,
        index: index,
        coupon: coupon,
        money: money,
        realPrice: 0
      })
  },
  // 提交订单
  submit:function(){
    var coming = this.data.coming;
    if(coming == 1){
      this.cartSure()
    }else if(coming==0){
      this.detailSure()
    }
     
  },
  // 购物车过来的，执行确认订单
  cartSure:function(){
    var cart_id = this.data.cart_id;
    var m_id = app.globalData.user.m_id;
    var user = this.data.address;
    var name = user.userName;
    var phone = user.telNumber;
    var address = user.provinceName + user.cityName + user.countyName + user.detailInfo;
    var cou_id = this.data.c_m_id;
    var shop_id =  this.data.shop_id;
    var remark = this.data.remark;
    if(name === undefined){
      wx.showModal({
        title: '提示',
        content: '请填写收货信息',
        showCancel:false
      })
    }else{
      wx.request({
        url: app.globalData.yuming + 'merchant.php/Api/ProductOrder/addOrder',
        data:{
          cart_id:cart_id,
          m_id:m_id,
          name:name,
          phone:phone,
          address:address,
          cou_id:cou_id,
          shop_id:shop_id,
          remark:remark
        },
        header:{
          "content-type":"application/x-www-form-urlencoded"
        },
        method:"POST",
        success:function(res){
          this.payment(res.data.data);  
        }.bind(this),
        fail:function(res){
          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel: false
          })
        }
      })
    }
  },
  // 详情页直接购买的，执行确认订单
  detailSure:function(){
    var p_id = this.data.p_id;
    var attr_val = this.data.attr_val; 
    var m_id = app.globalData.user.m_id;
    var user = this.data.address;
    var name = user.userName;
    var phone = user.telNumber;
    var address = user.provinceName + user.cityName + user.countyName + user.detailInfo;
    var cou_id = this.data.c_m_id;
    var shop_id = this.data.shop_id;
    var remark = this.data.remark;
    var num = this.data.num;
    var realPrice = this.data.realPrice;
    if (name === undefined) {
      wx.showModal({
        title: '提示',
        content: '请填写收货信息',
        showCancel: false
      })
    }else{
      wx.request({
        url: app.globalData.yuming + 'merchant.php/Api/ProductOrder/addOneOrder',
        data:{
            p_id:p_id,
            attr_val:attr_val,
            m_id: m_id,
            name: name,
            phone: phone,
            address: address,
            cou_id: cou_id,
            shop_id: shop_id,
            remark: remark,
            num: num
        },
        header:{
            "content-type":"application/x-www-form-urlencoded"
        },
        method:"POST",
        success:function(res){
          if(realPrice == 0){
            var order_sn = res.data.data.order_sn;
            wx.request({
              url: app.globalData.yuming + 'merchant.php/Api/Pay/otherPayOrder',
              data:{
                order_sn:order_sn
              },
              header:{
                "content-type":"application/x-www-form-urlencoded"
              },
              method:"POST",
              success:function(res){
                wx.setStorage({
                  key: 'order',
                  data: '2',
                  success: function () {
                    wx.redirectTo({
                      url: '/mine/myOrder/myOrder',
                    })
                  }
                })
              },
              fail:function(res){
                wx.showModal({
                  title: '提示',
                  content: res.data.message,
                  showCancel:false
                })
              }
            })
          }else{
            this.payment(res.data.data); 
          }
           
        }.bind(this),
        fail:function(res){
          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel:false
          })
        }
      })
    }
  },
  // 输入备注
  remark:function(e){
    var remark = e.detail.value;
    this.setData({
      remark:remark
    })
  },
  /**
   * 发起微信支付请求
   */
  payment:function(data){
    var order_sn = data.order_sn;
    console.log(order_sn)
    var arr = JSON.parse(data.pay_message);
    var timeStamp = arr['timeStamp'];
    var nonceStr = arr['nonceStr'];
    var packaged = arr['package'];
    var signType = arr['signType'];
    var paySign = arr['paySign'];
 
    wx.requestPayment({
      timeStamp: timeStamp,
      nonceStr: nonceStr,
      package: packaged,
      signType: signType,
      paySign: paySign,
      success:function(res){
      //  2 待发货
        wx.setStorage({
          key: 'order',
          data: '2',
          success: function () {
            wx.redirectTo({
              url: '/mine/myOrder/myOrder',
            })
          }
        })
      },
      fail:function(res){
      //  1 待付款
        if (res.errMsg == "requestPayment:fail cancel"){
          wx.request({
            url: app.globalData.yuming + 'merchant.php/Api/Pay/editOrder',
            data:{
              order_sn: order_sn
            },
            header:{
              "content-type":"application/x-www-form-urlencoded"
            },
            method:"POST",
            success:function(res){
              wx.setStorage({
                key: 'order',
                data: '1',
                success: function () {
                  wx.redirectTo({
                    url: '/mine/myOrder/myOrder',
                  })
                }
              })
            },
            fail:function(res){
              wx.showModal({
                title: '提示',
                content: res.data.message,
                showCancel:false
              })
            }
          })


         
        }else{
          wx.showModal({
            title: '提示',
            content: res.errMsg,
            showCancel:false
          })
        }
      }
    })
  }
})